using System;
using System.Reflection;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;

namespace DynamicFrom
{
    public partial class MainForm : Form
    {
        private Dictionary<string, Control> formControls;
        private object currentInstance;
        private List<Assembly> loadedAssemblies = new List<Assembly>();
        private Type selectedType; // 从配置中加载的类型

        public MainForm()
        {
            InitializeComponent();
            formControls = new Dictionary<string, Control>();

            // 绑定事件处理程序
            this.getDataButton.Click += GetDataButton_Click;
            this.settingsMenuItem.Click += SettingsButton_Click;
            this.editJsonMenuItem.Click += EditJsonButton_Click;
            this.reloadMenuItem.Click += GenerateButton_Click;

            // 显示按钮
            getDataButton.Visible = true;
            
            // 尝试加载默认配置
            LoadSelectedConfig();
            
            // 自动加载数据
            AutoLoadData();
        }

        /// <summary>
        /// 自动加载数据
        /// </summary>
        private void AutoLoadData()
        {
            try
            {
                if (selectedType == null)
                {
                    MessageBox.Show("未能从配置中加载类型，请检查配置文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 从JSON文件创建实例
                currentInstance = ConfigManager.CreateInstanceFromJson();

                // 清除之前的控件
                formPanel.Controls.Clear();
                formControls.Clear();

                // 生成表单
                GenerateForm(currentInstance);

                getDataButton.Enabled = true;
                
                // 更新按钮文本
                reloadMenuItem.Text = "🔄 重新加载(&R)";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"自动加载数据时出现错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载选定的配置文件
        /// </summary>
        private void LoadSelectedConfig()
        {
            try
            {
                // 从配置文件加载类型
                selectedType = ConfigManager.LoadTypeFromConfig();
                TypeConfiguration config = ConfigManager.LoadConfig();

                // 更新右侧标签显示类型信息
                string jsonInfo = string.IsNullOrEmpty(config.JsonFilePath) ? "" : $" (文件: {config.JsonFilePath})";
                rightLabel.Text = $"表单-{jsonInfo}:";

                // 禁用获取数据和重置按钮
                getDataButton.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置的类型时出错：{ex.Message}", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GenerateButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (selectedType == null)
                {
                    MessageBox.Show("未能从配置中加载类型，请检查配置文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 从JSON文件重新加载实例
                currentInstance = ConfigManager.CreateInstanceFromJson();

                // 清除之前的控件
                formPanel.Controls.Clear();
                formControls.Clear();

                // 重新生成表单
                GenerateForm(currentInstance);

                getDataButton.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重新加载数据时出现错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GenerateForm(object obj, string prefix = "", int startY = 20)
        {
            int yPosition = startY;

            if (string.IsNullOrEmpty(prefix))
            {
                // 添加标题
                var titleLabel = new Label
                {
                    Text = $"{obj.GetType().Name}表单编辑器",
                    Font = new Font("Microsoft YaHei", 14, FontStyle.Bold),
                    Location = new Point(20, yPosition),
                    Size = new Size(400, 30),
                    ForeColor = Color.FromArgb(51, 51, 51)
                };
                formPanel.Controls.Add(titleLabel);
                yPosition += 50;
            }

            // 获取所有公共属性
            var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var property in properties)
            {
                // 构建属性路径
                string propertyPath = string.IsNullOrEmpty(prefix)
                    ? property.Name
                    : $"{prefix}.{property.Name}";

                // 获取显示名称
                string displayName = property.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? property.Name;
                if (!string.IsNullOrEmpty(prefix))
                {
                    displayName = $"{displayName}";
                }

                // 获取属性值
                object value = property.GetValue(obj);

                // 检查是否是泛型集合类型
                bool isGenericList = property.PropertyType.IsGenericType && 
                    (property.PropertyType.GetGenericTypeDefinition() == typeof(List<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>));

                // 判断是否是基本类型的集合
                bool isPrimitiveTypeList = false;
                Type elementType = null;
                
                if (isGenericList)
                {
                    elementType = property.PropertyType.GetGenericArguments()[0];
                    isPrimitiveTypeList = elementType.IsPrimitive || 
                                         elementType == typeof(string) || 
                                         elementType == typeof(decimal) || 
                                         elementType == typeof(DateTime);
                }

                // 根据属性类型生成不同的表单元素
                if ((property.PropertyType.IsClass &&
                    property.PropertyType != typeof(string) &&
                    !property.PropertyType.IsArray &&
                    !typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) ||
                    isGenericList)
                {
                    // 对象类型或集合类型的属性
                    if (value == null)
                    {
                        try
                        {
                            value = Activator.CreateInstance(property.PropertyType);
                            property.SetValue(obj, value);
                        }
                        catch (Exception)
                        {
                            // 如果无法创建实例，则跳过该属性
                            continue;
                        }
                    }

                    // 创建分组标签
                    var groupLabel = new Label
                    {
                        Text = displayName,
                        Font = new Font("Microsoft YaHei", 10, FontStyle.Bold),
                        Location = new Point(20, yPosition),
                        Size = new Size(400, 25),
                        ForeColor = Color.FromArgb(51, 51, 51)
                    };
                    formPanel.Controls.Add(groupLabel);
                    yPosition += 30;

                    // 添加分组线
                    var separator = new Panel
                    {
                        Location = new Point(20, yPosition),
                        Size = new Size(formPanel.Width - 40, 1),
                        BackColor = Color.FromArgb(224, 224, 224)
                    };
                    formPanel.Controls.Add(separator);
                    yPosition += 10;

                    // 处理泛型集合类型
                    if (isGenericList)
                    {
                        // 获取集合实例
                        IList collection = (IList)value;
                        
                        // 如果集合为空，添加一个默认项
                        if (collection.Count == 0)
                        {
                            try
                            {
                                var newItem = Activator.CreateInstance(elementType);
                                collection.Add(newItem);
                            }
                            catch (Exception)
                            {
                                // 如果无法创建实例，则跳过
                                continue;
                            }
                        }

                        // 基本类型的集合使用简单的文本框编辑
                        if (isPrimitiveTypeList)
                        {
                            // 将集合转换为逗号分隔的字符串
                            string collectionText = string.Join(", ", collection.Cast<object>());
                            
                            // 创建说明标签
                            var infoLabel = new Label
                            {
                                Text = "请输入以逗号分隔的值列表:",
                                Location = new Point(40, yPosition),
                                Size = new Size(formPanel.Width - 60, 20),
                                ForeColor = Color.FromArgb(70, 70, 70)
                            };
                            formPanel.Controls.Add(infoLabel);
                            yPosition += 25;
                            
                            // 创建文本框
                            var textBox = new TextBox
                            {
                                Text = collectionText,
                                Location = new Point(40, yPosition),
                                Size = new Size(formPanel.Width - 60, 30),
                                Font = new Font("Consolas", 9),
                                Tag = new { ElementType = elementType, Collection = collection }
                            };
                            formPanel.Controls.Add(textBox);
                            
                            // 保存控件引用
                            formControls[propertyPath] = textBox;
                            
                            yPosition += 40;
                        }
                        else
                        {
                            // 对于复杂类型的集合，为每个项创建表单
                            for (int i = 0; i < collection.Count; i++)
                            {
                                var item = collection[i];
                                
                                // 创建项目标题和删除按钮的面板
                                var itemHeaderPanel = new Panel
                                {
                                    Location = new Point(40, yPosition),
                                    Size = new Size(formPanel.Width - 60, 25),
                                    Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                                };
                                formPanel.Controls.Add(itemHeaderPanel);
                                
                                // 创建项目标题
                                var itemLabel = new Label
                                {
                                    Text = $"项目 #{i + 1}",
                                    Font = new Font("Microsoft YaHei", 9, FontStyle.Bold),
                                    Location = new Point(0, 0),
                                    Size = new Size(300, 20),
                                    ForeColor = Color.FromArgb(70, 70, 70)
                                };
                                itemHeaderPanel.Controls.Add(itemLabel);
                                
                                // 创建删除按钮 - 始终显示删除按钮
                                var deleteButton = new Button
                                {
                                    Text = "删除",
                                    Location = new Point(itemHeaderPanel.Width - 80, 0),
                                    Size = new Size(60, 23),
                                    ForeColor = Color.Red,
                                    Tag = new { PropertyPath = propertyPath, Index = i, Collection = collection }
                                };
                                deleteButton.Click += (sender, e) => {
                                    var btnData = (dynamic)((Button)sender).Tag;
                                    string path = btnData.PropertyPath;
                                    int index = btnData.Index;
                                    IList list = btnData.Collection;
                                    
                                    try
                                    {
                                        // 确认是否删除
                                        var result = MessageBox.Show($"确定要删除项目 #{index + 1} 吗？", "确认删除", 
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                                            
                                        if (result == DialogResult.Yes)
                                        {
                                            // 检查删除后集合是否为空
                                            if (list.Count <= 1)
                                            {
                                                // 如果只有一个项目，不允许删除
                                                MessageBox.Show("不能删除唯一的项目。集合中必须至少保留一个项目。", 
                                                    "无法删除", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                                return;
                                            }
                                            
                                            // 先保存当前表单的数据
                                            UpdateInstanceFromForm(currentInstance);
                                            
                                            // 从集合中移除项目
                                            list.RemoveAt(index);
                                            
                                            // 重新生成表单
                                            formPanel.Controls.Clear();
                                            formControls.Clear();
                                            GenerateForm(currentInstance);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show($"删除项目时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                };
                                itemHeaderPanel.Controls.Add(deleteButton);
                                
                                yPosition += 25;
                                
                                // 递归生成此项的表单
                                yPosition = GenerateNestedForm(item, $"{propertyPath}[{i}]", yPosition);
                                
                                // 添加项目分隔线
                                if (i < collection.Count - 1)
                                {
                                    var itemSeparator = new Panel
                                    {
                                        Location = new Point(40, yPosition),
                                        Size = new Size(formPanel.Width - 60, 1),
                                        BackColor = Color.FromArgb(240, 240, 240)
                                    };
                                    formPanel.Controls.Add(itemSeparator);
                                    yPosition += 10;
                                }
                            }
                        }
                        
                        // 添加"添加项目"按钮 (对于基本类型集合，不需要添加按钮，因为通过文本框编辑)
                        if (!isPrimitiveTypeList)
                        {
                            var addButton = new Button
                            {
                                Text = "添加项目",
                                Location = new Point(40, yPosition),
                                Size = new Size(100, 30),
                                Tag = new { PropertyPath = propertyPath, ElementType = elementType, Collection = collection }
                            };
                            addButton.Click += (sender, e) => {
                                var btnData = (dynamic)((Button)sender).Tag;
                                string path = btnData.PropertyPath;
                                Type type = btnData.ElementType;
                                IList list = btnData.Collection;
                                
                                try
                                {
                                    // 先保存当前表单的数据
                                    UpdateInstanceFromForm(currentInstance);
                                    
                                    // 创建新项并添加到集合
                                    var newItem = Activator.CreateInstance(type);
                                    list.Add(newItem);
                                    
                                    // 重新生成表单
                                    formPanel.Controls.Clear();
                                    formControls.Clear();
                                    GenerateForm(currentInstance);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show($"添加项目时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            };
                            formPanel.Controls.Add(addButton);
                            yPosition += 40;
                        }
                    }
                    else
                    {
                        // 递归生成嵌套对象的表单
                        yPosition = GenerateNestedForm(value, propertyPath, yPosition);
                    }
                }
                else
                {
                    // 基本类型属性
                    yPosition = GeneratePropertyField(property, value, propertyPath, displayName, yPosition);
                }
            }
        }

        private int GenerateNestedForm(object obj, string prefix, int yPosition)
        {
            // 缩进嵌套表单
            int indent = 20;
            var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            
            // 声明分组相关变量
            Panel groupPanel = null;
            int groupStartY = 0;

            foreach (var property in properties)
            {
                string propertyPath = $"{prefix}.{property.Name}";
                string displayName = property.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? property.Name;
                object value = property.GetValue(obj);

                // 检查是否是泛型集合类型
                bool isGenericList = property.PropertyType.IsGenericType && 
                    (property.PropertyType.GetGenericTypeDefinition() == typeof(List<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>));

                // 判断是否是基本类型的集合
                bool isPrimitiveTypeList = false;
                Type elementType = null;
                
                if (isGenericList)
                {
                    elementType = property.PropertyType.GetGenericArguments()[0];
                    isPrimitiveTypeList = elementType.IsPrimitive || 
                                         elementType == typeof(string) || 
                                         elementType == typeof(decimal) || 
                                         elementType == typeof(DateTime);
                }

                if ((property.PropertyType.IsClass &&
                    property.PropertyType != typeof(string) &&
                    !property.PropertyType.IsArray &&
                    !typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) ||
                    isGenericList)
                {
                    // 嵌套对象或集合
                    if (value == null)
                    {
                        try
                        {
                            value = Activator.CreateInstance(property.PropertyType);
                            property.SetValue(obj, value);
                        }
                        catch (Exception)
                        {
                            // 如果无法创建实例，则跳过该属性
                            continue;
                        }
                    }

                    // 创建嵌套分组标签
                    var nestedGroupLabel = new Label
                    {
                        Text = $"▶ {displayName}",
                        Font = new Font("Microsoft YaHei", 10, FontStyle.Bold),
                        Location = new Point(20 + indent, yPosition),
                        Size = new Size(400 - indent, 25),
                        ForeColor = Color.FromArgb(0, 122, 204)
                    };
                    formPanel.Controls.Add(nestedGroupLabel);
                    yPosition += 25;

                    // 记录分组面板的起始位置
                    groupStartY = yPosition;
                    
                    // 添加嵌套分组背景面板
                    groupPanel = new Panel
                    {
                        Location = new Point(20 + indent, yPosition),
                        Size = new Size(formPanel.Width - 40 - indent, 0), // 高度稍后调整
                        BackColor = Color.FromArgb(248, 249, 250),
                        BorderStyle = BorderStyle.FixedSingle,
                        Padding = new Padding(10, 5, 10, 5)
                    };
                    formPanel.Controls.Add(groupPanel);
                    groupPanel.BringToFront();
                    formPanel.Controls.SetChildIndex(groupPanel, formPanel.Controls.Count - 1);
                    
                    // 处理泛型集合类型
                    if (isGenericList)
                    {
                        // 获取集合实例
                        IList collection = (IList)value;
                        
                        // 如果集合为空，添加一个默认项
                        if (collection.Count == 0)
                        {
                            try
                            {
                                var newItem = Activator.CreateInstance(elementType);
                                collection.Add(newItem);
                            }
                            catch (Exception)
                            {
                                // 如果无法创建实例，则跳过
                                continue;
                            }
                        }

                        // 基本类型的集合使用简单的文本框编辑
                        if (isPrimitiveTypeList)
                        {
                            // 将集合转换为逗号分隔的字符串
                            string collectionText = string.Join(", ", collection.Cast<object>());
                            
                            // 创建说明标签
                            var infoLabel = new Label
                            {
                                Text = "请输入以逗号分隔的值列表:",
                                Location = new Point(40 + indent, yPosition),
                                Size = new Size(formPanel.Width - 60 - indent, 20),
                                ForeColor = Color.FromArgb(70, 70, 70)
                            };
                            formPanel.Controls.Add(infoLabel);
                            yPosition += 25;
                            
                            // 创建文本框
                            var textBox = new TextBox
                            {
                                Text = collectionText,
                                Location = new Point(40 + indent, yPosition),
                                Size = new Size(formPanel.Width - 60 - indent, 30),
                                Font = new Font("Consolas", 9),
                                Tag = new { ElementType = elementType, Collection = collection }
                            };
                            formPanel.Controls.Add(textBox);
                            
                            // 保存控件引用
                            formControls[propertyPath] = textBox;
                            
                            yPosition += 40;
                        }
                        else
                        {
                            // 为集合中的每个项创建表单
                            for (int i = 0; i < collection.Count; i++)
                            {
                                var item = collection[i];
                                
                                // 创建项目标题和删除按钮的面板
                                var itemHeaderPanel = new Panel
                                {
                                    Location = new Point(40 + indent, yPosition),
                                    Size = new Size(formPanel.Width - 60 - indent, 25),
                                    Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                                };
                                formPanel.Controls.Add(itemHeaderPanel);
                                
                                // 创建项目标题
                                var itemLabel = new Label
                                {
                                    Text = $"项目 #{i + 1}",
                                    Font = new Font("Microsoft YaHei", 9, FontStyle.Bold),
                                    Location = new Point(0, 0),
                                    Size = new Size(300 - indent, 20),
                                    ForeColor = Color.FromArgb(70, 70, 70)
                                };
                                itemHeaderPanel.Controls.Add(itemLabel);
                                
                                // 创建删除按钮 - 始终显示删除按钮
                                var deleteButton = new Button
                                {
                                    Text = "删除",
                                    Location = new Point(itemHeaderPanel.Width - 80, 0),
                                    Size = new Size(60, 23),
                                    ForeColor = Color.Red,
                                    Tag = new { PropertyPath = propertyPath, Index = i, Collection = collection }
                                };
                                deleteButton.Click += (sender, e) => {
                                    var btnData = (dynamic)((Button)sender).Tag;
                                    string path = btnData.PropertyPath;
                                    int index = btnData.Index;
                                    IList list = btnData.Collection;
                                    
                                    try
                                    {
                                        // 确认是否删除
                                        var result = MessageBox.Show($"确定要删除项目 #{index + 1} 吗？", "确认删除", 
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                                            
                                        if (result == DialogResult.Yes)
                                        {
                                            // 检查删除后集合是否为空
                                            if (list.Count <= 1)
                                            {
                                                // 如果只有一个项目，不允许删除
                                                MessageBox.Show("不能删除唯一的项目。集合中必须至少保留一个项目。", 
                                                    "无法删除", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                                return;
                                            }
                                            
                                            // 先保存当前表单的数据
                                            UpdateInstanceFromForm(currentInstance);
                                            
                                            // 从集合中移除项目
                                            list.RemoveAt(index);
                                            
                                            // 重新生成表单
                                            formPanel.Controls.Clear();
                                            formControls.Clear();
                                            GenerateForm(currentInstance);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show($"删除项目时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                };
                                itemHeaderPanel.Controls.Add(deleteButton);
                                
                                yPosition += 25;
                                
                                // 递归生成此项的表单
                                yPosition = GenerateNestedForm(item, $"{propertyPath}[{i}]", yPosition);
                                
                                // 添加项目分隔线
                                if (i < collection.Count - 1)
                                {
                                    var itemSeparator = new Panel
                                    {
                                        Location = new Point(40 + indent, yPosition),
                                        Size = new Size(formPanel.Width - 60 - indent, 1),
                                        BackColor = Color.FromArgb(240, 240, 240)
                                    };
                                    formPanel.Controls.Add(itemSeparator);
                                    yPosition += 10;
                                }
                            }
                        }
                        
                        // 添加"添加项目"按钮 (对于基本类型集合，不需要添加按钮，因为通过文本框编辑)
                        if (!isPrimitiveTypeList)
                        {
                            var addButton = new Button
                            {
                                Text = "添加项目",
                                Location = new Point(40 + indent, yPosition),
                                Size = new Size(100, 30),
                                Tag = new { PropertyPath = propertyPath, ElementType = elementType, Collection = collection }
                            };
                            addButton.Click += (sender, e) => {
                                var btnData = (dynamic)((Button)sender).Tag;
                                string path = btnData.PropertyPath;
                                Type type = btnData.ElementType;
                                IList list = btnData.Collection;
                                
                                try
                                {
                                    // 先保存当前表单的数据
                                    UpdateInstanceFromForm(currentInstance);
                                    
                                    // 创建新项并添加到集合
                                    var newItem = Activator.CreateInstance(type);
                                    list.Add(newItem);
                                    
                                    // 重新生成表单
                                    formPanel.Controls.Clear();
                                    formControls.Clear();
                                    GenerateForm(currentInstance);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show($"添加项目时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            };
                            formPanel.Controls.Add(addButton);
                            yPosition += 40;
                        }
                    }
                    else
                    {
                        // 递归生成更深层嵌套
                        yPosition = GenerateNestedForm(value, propertyPath, yPosition);
                    }
                }
                else
                {
                    // 缩进的基本属性
                    yPosition = GeneratePropertyField(property, value, propertyPath, displayName, yPosition, indent);
                }
            }

            // 调整分组面板的大小
            if (groupPanel != null)
            {
                int groupHeight = yPosition - groupStartY + 10;
                groupPanel.Size = new Size(groupPanel.Width, groupHeight);
            }
            
            // 添加额外的间距
            yPosition += 10;
            return yPosition;
        }

        private int GeneratePropertyField(PropertyInfo property, object value, string path, string displayName, int yPosition, int indent = 0)
        {
            // 显示标签
            var descriptionAttr = property.GetCustomAttribute<DescriptionAttribute>();
            string description = descriptionAttr?.Description;

            var labelText = !string.IsNullOrEmpty(description)
                ? $"{displayName} ({description})"
                : displayName;

            // 根据缩进级别设置不同的字体和颜色
            Font labelFont;
            Color labelColor;
            if (indent == 0)
            {
                // 顶级字段
                labelFont = new Font("Microsoft YaHei", 10, FontStyle.Bold);
                labelColor = Color.FromArgb(51, 51, 51);
            }
            else if (indent == 20)
            {
                // 二级字段
                labelFont = new Font("Microsoft YaHei", 9, FontStyle.Bold);
                labelColor = Color.FromArgb(68, 68, 68);
            }
            else
            {
                // 三级及以下字段
                labelFont = new Font("Microsoft YaHei", 9);
                labelColor = Color.FromArgb(85, 85, 85);
            }

            var label = new Label
            {
                Text = labelText,
                Location = new Point(20 + indent, yPosition),
                Size = new Size(150, 25),
                TextAlign = ContentAlignment.MiddleLeft,
                Font = labelFont,
                ForeColor = labelColor
            };
            formPanel.Controls.Add(label);

            // 创建输入控件
            Control control = CreateControlForProperty(property, value);
            if (control != null)
            {
                control.Location = new Point(180 + indent, yPosition);
                
                // 调整控件大小，根据控件类型设置不同高度
                if (control is TextBox textBox && textBox.Multiline)
                {
                    // 多行文本框使用更大的高度
                    control.Size = new Size(formPanel.Width - 220 - indent, textBox.Height);
                }
                else if (control is CheckBox)
                {
                    // CheckBox使用固定的小尺寸，减少点击区域
                    control.Size = new Size(16, 16);
                    control.Location = new Point(180 + indent, yPosition + 7); // 垂直居中
                }
                else
                {
                    // 其他控件使用标准高度
                    control.Size = new Size(formPanel.Width - 220 - indent, 30);
                }
                
                formPanel.Controls.Add(control);

                // 保存控件引用
                formControls[path] = control;
            }

            // 添加验证标签（如果有验证特性）
            var validationAttributes = property.GetCustomAttributes()
                .Where(attr => attr is ValidationAttribute)
                .Cast<ValidationAttribute>()
                .ToList();

            if (validationAttributes.Any())
            {
                var validationLabel = new Label
                {
                    Text = string.Join(", ", validationAttributes.Select(attr => attr.ErrorMessage ?? attr.GetType().Name)),
                    Location = new Point(180 + indent, yPosition + (control is TextBox textBox && textBox.Multiline ? control.Height : 30)),
                    Size = new Size(formPanel.Width - 220 - indent, 20),
                    ForeColor = Color.FromArgb(220, 53, 69),
                    Font = new Font("Microsoft YaHei", 8)
                };
                formPanel.Controls.Add(validationLabel);
                yPosition += 20;
            }

            // 根据控件高度调整下一个控件的位置
            if (control is TextBox textBox2 && textBox2.Multiline)
            {
                return yPosition + textBox2.Height + 15;
            }
            else
            {
                return yPosition + 40; // 增加了默认间距
            }
        }

        private Control CreateControlForProperty(PropertyInfo property, object value)
        {
            Type propertyType = property.PropertyType;

            // 处理可空类型
            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                propertyType = propertyType.GetGenericArguments()[0];
            }

            // 处理数组类型，特别是 double[] 数组
            if (propertyType.IsArray)
            {
                Type elementType = propertyType.GetElementType();
                
                // 数组内容转换为字符串展示
                string arrayText = "";
                if (value != null)
                {
                    Array array = (Array)value;
                    arrayText = string.Join(", ", array.Cast<object>());
                }
                
                var textBox = new TextBox
                {
                    Text = arrayText,
                    Font = new Font("Consolas", 9),
                    Height = 50,
                    Multiline = true,
                    ScrollBars = ScrollBars.Vertical,
                    Tag = elementType  // 保存数组的元素类型以便后续转换
                };
                
                return textBox;
            }

            if (propertyType == typeof(string))
            {
                return CreateTextControl(value?.ToString());
            }
            else             if (propertyType == typeof(int) || propertyType == typeof(long) ||
                     propertyType == typeof(short) || propertyType == typeof(byte))
            {
                var numericUpDown = new NoWheelNumericUpDown
                {
                    Minimum = decimal.MinValue,
                    Maximum = decimal.MaxValue,
                    DecimalPlaces = 0,
                    Value = Convert.ToDecimal(value ?? 0),
                    Font = new Font("Consolas", 9)
                };

                // 应用Range特性（如果有）
                var rangeAttr = property.GetCustomAttribute<RangeAttribute>();
                if (rangeAttr != null)
                {
                    numericUpDown.Minimum = Convert.ToDecimal(rangeAttr.Minimum);
                    numericUpDown.Maximum = Convert.ToDecimal(rangeAttr.Maximum);
                }

                return numericUpDown;
            }
            else if (propertyType == typeof(decimal) || propertyType == typeof(double) || propertyType == typeof(float))
            {
                var numericUpDown = new NoWheelNumericUpDown
                {
                    Minimum = decimal.MinValue,
                    Maximum = decimal.MaxValue,
                    DecimalPlaces = 2,
                    Value = Convert.ToDecimal(value ?? 0),
                    Font = new Font("Consolas", 9)
                };

                // 应用Range特性（如果有）
                var rangeAttr = property.GetCustomAttribute<RangeAttribute>();
                if (rangeAttr != null)
                {
                    numericUpDown.Minimum = Convert.ToDecimal(rangeAttr.Minimum);
                    numericUpDown.Maximum = Convert.ToDecimal(rangeAttr.Maximum);
                }

                return numericUpDown;
            }
            else if (propertyType == typeof(bool))
            {
                var checkBox = new NoWheelCheckBox
                {
                    Checked = (bool)(value ?? false),
                    Text = "",
                    FlatStyle = FlatStyle.Flat,
                    BackColor = Color.White,
                    ForeColor = Color.Black
                };
                
                return checkBox;
            }
            else if (propertyType == typeof(DateTime))
            {
                var dateTimePicker = new NoWheelDateTimePicker
                {
                    Value = (DateTime)(value ?? DateTime.Now),
                    Format = DateTimePickerFormat.Short,
                    Font = new Font("Consolas", 9)
                };

                return dateTimePicker;
            }
            else if (propertyType.IsEnum)
            {
                var comboBox = new NoWheelComboBox
                {
                    DropDownStyle = ComboBoxStyle.DropDownList,
                    Font = new Font("Consolas", 9)
                };

                foreach (var enumValue in Enum.GetValues(propertyType))
                {
                    var field = propertyType.GetField(enumValue.ToString());
                    var description = field?.GetCustomAttribute<DescriptionAttribute>()?.Description;

                    var item = new ComboBoxItem
                    {
                        Value = enumValue,
                        Text = !string.IsNullOrEmpty(description) ? description : enumValue.ToString()
                    };

                    comboBox.Items.Add(item);
                    if (enumValue.Equals(value))
                    {
                        comboBox.SelectedItem = item;
                    }
                }

                if (comboBox.SelectedIndex == -1 && comboBox.Items.Count > 0)
                {
                    comboBox.SelectedIndex = 0;
                }

                return comboBox;
            }

            // 默认为文本框
            return CreateTextControl(value?.ToString());
        }



        private Control CreateTextControl(string value)
        {
            if (value != null && value.Contains('\n'))
            {
                // 多行文本
                return new TextBox
                {
                    Multiline = true,
                    ScrollBars = ScrollBars.Vertical,
                    Text = value,
                    Font = new Font("Consolas", 9),
                    Height = 100  // 增加默认高度，从80增加到100
                };
            }
            else
            {
                // 单行文本
                return new TextBox
                {
                    Text = value ?? string.Empty,
                    Font = new Font("Consolas", 9),
                    Height = 30  // 增加单行文本框高度，从默认高度增加到30
                };
            }
        }

        private void GetDataButton_Click(object sender, EventArgs e)
        {
            if (currentInstance == null)
            {
                MessageBox.Show("请先生成表单", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                // 从表单控件更新对象属性值
                UpdateInstanceFromForm(currentInstance);

                // 生成预览内容
                string previewContent = GeneratePreviewContent(currentInstance);
                
                // 验证JSON格式
                string errorMessage;
                if (!ValidateJsonFormatWithDetails(previewContent, out errorMessage))
                {
                    MessageBox.Show($"生成的JSON格式无效：\n{errorMessage}", "JSON格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 显示预览对话框
                DialogResult result = ShowPreviewDialog(previewContent);
                
                if (result == DialogResult.OK)
                {
                    // 用户确认保存
                    bool saveSuccess = ConfigManager.SaveInstanceToJson(currentInstance);

                    if (saveSuccess)
                    {
                        MessageBox.Show("已成功将更改保存到JSON文件", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                // 检查是否是数据格式转换错误
                if (ex.Message.Contains("无法将值") || ex.Message.Contains("转换为") || ex.Message.Contains("Input string was not in a correct"))
                {
                    MessageBox.Show($"表单数据格式错误：\n{ex.Message}", "数据格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show($"获取数据时出现错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return;
            }
        }

        /// <summary>
        /// 设置按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void SettingsButton_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前配置
                TypeConfiguration currentConfig = ConfigManager.LoadConfig();
                
                // 创建配置设置窗体
                using (ConfigSettingsForm settingsForm = new ConfigSettingsForm(
                    currentConfig?.ClassName ?? "", 
                    currentConfig?.JsonFilePath ?? ""))
                {
                    // 显示设置窗体
                    if (settingsForm.ShowDialog() == DialogResult.OK)
                    {
                        // 创建新的配置对象
                        TypeConfiguration newConfig = new TypeConfiguration
                        {
                            ClassName = settingsForm.ClassName,
                            JsonFilePath = settingsForm.JsonFilePath
                        };

                        // 保存配置
                        bool saveResult = ConfigManager.SaveConfig(newConfig);
                        if (saveResult)
                        {
                            MessageBox.Show("配置已成功保存", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 重新加载配置
                            LoadSelectedConfig();
                            
                            // 重新加载数据
                            AutoLoadData();
                        }
                        else
                        {
                            MessageBox.Show("保存配置时出现错误", "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开设置窗口时出现错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 编辑JSON文件按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void EditJsonButton_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前配置
                TypeConfiguration config = ConfigManager.LoadConfig();
                if (config == null || string.IsNullOrEmpty(config.JsonFilePath))
                {
                    MessageBox.Show("未配置JSON文件路径，请先在设置中配置", "配置错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 查找JSON文件
                string jsonFilePath = FindJsonFile(config.JsonFilePath);
                if (string.IsNullOrEmpty(jsonFilePath) || !File.Exists(jsonFilePath))
                {
                    MessageBox.Show($"找不到JSON文件：{config.JsonFilePath}", "文件不存在", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 读取JSON文件内容
                System.Text.Encoding fileEncoding = DetectFileEncoding(jsonFilePath);
                string jsonContent = File.ReadAllText(jsonFilePath, fileEncoding);

                // 验证JSON格式
                string errorMessage;
                if (!ValidateJsonFormatWithDetails(jsonContent, out errorMessage))
                {
                    MessageBox.Show($"JSON文件格式错误：\n{errorMessage}", "JSON格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 显示JSON编辑对话框
                DialogResult result = ShowJsonEditDialog(jsonContent, jsonFilePath);

                if (result == DialogResult.OK)
                {
                    // 重新加载数据
                    AutoLoadData();
                    MessageBox.Show("JSON文件已更新，数据已重新加载", "更新成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"编辑JSON文件时出现错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 验证JSON字符串格式
        /// </summary>
        /// <param name="jsonString">要验证的JSON字符串</param>
        /// <returns>如果JSON格式有效返回true，否则返回false</returns>
        private bool ValidateJsonFormat(string jsonString)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(jsonString))
                {
                    return false;
                }

                // 尝试解析JSON字符串
                var parsedJson = Newtonsoft.Json.Linq.JToken.Parse(jsonString);
                
                // 如果解析成功，说明JSON格式正确
                return true;
            }
            catch (Newtonsoft.Json.JsonReaderException ex)
            {
                // JSON格式错误
                System.Diagnostics.Debug.WriteLine($"JSON格式验证失败: {ex.Message}");
                return false;
            }
            catch (Exception ex)
            {
                // 其他错误
                System.Diagnostics.Debug.WriteLine($"JSON验证时发生未知错误: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 验证JSON字符串格式并返回详细错误信息
        /// </summary>
        /// <param name="jsonString">要验证的JSON字符串</param>
        /// <param name="errorMessage">输出错误信息</param>
        /// <returns>如果JSON格式有效返回true，否则返回false</returns>
        private bool ValidateJsonFormatWithDetails(string jsonString, out string errorMessage)
        {
            errorMessage = "";
            
            try
            {
                if (string.IsNullOrWhiteSpace(jsonString))
                {
                    errorMessage = "JSON字符串为空";
                    return false;
                }

                // 尝试解析JSON字符串
                var parsedJson = Newtonsoft.Json.Linq.JToken.Parse(jsonString);
                
                // 如果解析成功，说明JSON格式正确
                return true;
            }
            catch (Newtonsoft.Json.JsonReaderException ex)
            {
                // JSON格式错误
                errorMessage = $"JSON格式错误: {ex.Message}";
                System.Diagnostics.Debug.WriteLine($"JSON格式验证失败: {ex.Message}");
                return false;
            }
            catch (Exception ex)
            {
                // 其他错误
                errorMessage = $"JSON验证时发生未知错误: {ex.Message}";
                System.Diagnostics.Debug.WriteLine($"JSON验证时发生未知错误: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 生成预览内容
        /// </summary>
        /// <param name="instance">要预览的实例</param>
        /// <returns>格式化的预览内容</returns>
        private string GeneratePreviewContent(object instance)
        {
            try
            {
                // 使用JSON序列化生成格式化的预览内容
                string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(instance, Newtonsoft.Json.Formatting.Indented);
                return jsonContent;
            }
            catch (Exception ex)
            {
                return $"生成预览内容时出错: {ex.Message}";
            }
        }

        /// <summary>
        /// 显示预览对话框
        /// </summary>
        /// <param name="previewContent">预览内容</param>
        /// <returns>用户的选择结果</returns>
        private DialogResult ShowPreviewDialog(string previewContent)
        {
            // 获取原始数据用于对比
            string originalContent = "";
            try
            {
                // 获取配置信息
                var config = ConfigManager.LoadConfig();
                if (config != null && !string.IsNullOrEmpty(config.JsonFilePath))
                {
                    // 尝试直接从JSON文件读取原始内容
                    string jsonFilePath = FindJsonFile(config.JsonFilePath);
                    if (!string.IsNullOrEmpty(jsonFilePath) && File.Exists(jsonFilePath))
                    {
                        // 直接读取JSON文件内容
                        System.Text.Encoding fileEncoding = DetectFileEncoding(jsonFilePath);
                        originalContent = File.ReadAllText(jsonFilePath, fileEncoding);
                    }
                    else
                    {
                        // 如果无法直接读取文件，尝试通过ConfigManager创建实例
                        var originalInstance = ConfigManager.CreateInstanceFromJson();
                        if (originalInstance != null)
                        {
                            originalContent = Newtonsoft.Json.JsonConvert.SerializeObject(originalInstance, Newtonsoft.Json.Formatting.Indented);
                        }
                    }
                }
                else
                {
                    // 如果配置为空，尝试通过ConfigManager创建实例
                    var originalInstance = ConfigManager.CreateInstanceFromJson();
                    if (originalInstance != null)
                    {
                        originalContent = Newtonsoft.Json.JsonConvert.SerializeObject(originalInstance, Newtonsoft.Json.Formatting.Indented);
                    }
                }
            }
            catch (Exception ex)
            {
                // 如果无法获取原始数据，显示错误信息
                originalContent = $"// 无法读取原始数据: {ex.Message}";
            }

            // 创建预览窗体
            Form previewForm = new Form
            {
                Text = "保存预览 - 修改前后对照",
                Size = new Size(1200, 700),
                StartPosition = FormStartPosition.CenterParent,
                FormBorderStyle = FormBorderStyle.Sizable,
                MaximizeBox = true,
                MinimizeBox = true,
                MinimumSize = new Size(800, 500)
            };

            // 创建说明标签
            Label infoLabel = new Label
            {
                Text = "请确认以下修改内容是否正确，确认后将保存到JSON文件:",
                Location = new Point(10, 10),
                Size = new Size(1160, 20),
                Font = new Font("Microsoft YaHei", 9),
                Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
            };
            previewForm.Controls.Add(infoLabel);

            // 创建分割容器
            SplitContainer splitContainer = new SplitContainer
            {
                Location = new Point(10, 35),
                Size = new Size(1160, 550),
                Orientation = Orientation.Vertical,
                SplitterDistance = 580,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            // 左侧面板 - 原始数据
            Panel leftPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.FromArgb(248, 249, 250)
            };

            Label originalLabel = new Label
            {
                Text = "原始数据:",
                Dock = DockStyle.Top,
                Height = 24,
                Font = new Font("Microsoft YaHei", 9, FontStyle.Bold),
                ForeColor = Color.FromArgb(73, 80, 87)
            };
            leftPanel.Controls.Add(originalLabel);

            RichTextBox originalTextBox = new RichTextBox
            {
                Dock = DockStyle.Fill,
                Font = new Font("Consolas", 9),
                ReadOnly = true,
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle
            };
            leftPanel.Controls.Add(originalTextBox);
            leftPanel.Controls.SetChildIndex(originalTextBox, 0); // RichTextBox在下，Label在上

            // 右侧面板 - 修改后数据
            Panel rightPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.FromArgb(248, 249, 250)
            };

            Label modifiedLabel = new Label
            {
                Text = "修改后数据:",
                Dock = DockStyle.Top,
                Height = 24,
                Font = new Font("Microsoft YaHei", 9, FontStyle.Bold),
                ForeColor = Color.FromArgb(73, 80, 87)
            };
            rightPanel.Controls.Add(modifiedLabel);

            RichTextBox modifiedTextBox = new RichTextBox
            {
                Dock = DockStyle.Fill,
                Font = new Font("Consolas", 9),
                ReadOnly = true,
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle
            };
            rightPanel.Controls.Add(modifiedTextBox);
            rightPanel.Controls.SetChildIndex(modifiedTextBox, 0);

            splitContainer.Panel1.Controls.Add(leftPanel);
            splitContainer.Panel2.Controls.Add(rightPanel);
            previewForm.Controls.Add(splitContainer);

            // 记录高亮位置
            List<int> highlightStarts = new List<int>();
            List<int> highlightLengths = new List<int>();

            // 设置文本内容并高亮差异（收集高亮位置）
            SetJsonWithHighlights(originalTextBox, originalContent, modifiedTextBox, previewContent, highlightStarts, highlightLengths);

            // 当前高亮索引
            int currentHighlightIndex = 0;

            // 创建按钮面板
            Panel buttonPanel = new Panel
            {
                Location = new Point(10, 595),
                Size = new Size(1160, 50),
                Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            // 上一个高亮按钮
            Button prevHighlightButton = new Button
            {
                Text = "上一个高亮",
                Location = new Point(20, 10),
                Size = new Size(100, 30),
                BackColor = Color.FromArgb(0, 122, 204),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };
            prevHighlightButton.Click += (s, e) =>
            {
                if (highlightStarts.Count == 0) return;
                currentHighlightIndex = (currentHighlightIndex - 1 + highlightStarts.Count) % highlightStarts.Count;
                modifiedTextBox.Select(highlightStarts[currentHighlightIndex], highlightLengths[currentHighlightIndex]);
                modifiedTextBox.SelectionBackColor = Color.FromArgb(255, 255, 0); // 亮黄色背景
                modifiedTextBox.SelectionColor = Color.Black;
                modifiedTextBox.ScrollToCaret();
                modifiedTextBox.Focus();
            };
            buttonPanel.Controls.Add(prevHighlightButton);

            // 下一个高亮按钮
            Button nextHighlightButton = new Button
            {
                Text = "下一个高亮",
                Location = new Point(130, 10),
                Size = new Size(100, 30),
                BackColor = Color.FromArgb(0, 122, 204),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };
            nextHighlightButton.Click += (s, e) =>
            {
                if (highlightStarts.Count == 0) return;
                currentHighlightIndex = (currentHighlightIndex + 1) % highlightStarts.Count;
                modifiedTextBox.Select(highlightStarts[currentHighlightIndex], highlightLengths[currentHighlightIndex]);
                modifiedTextBox.SelectionBackColor = Color.FromArgb(255, 255, 0); // 亮黄色背景
                modifiedTextBox.SelectionColor = Color.Black;
                modifiedTextBox.ScrollToCaret();
                modifiedTextBox.Focus();
            };
            buttonPanel.Controls.Add(nextHighlightButton);

            // 确认按钮
            Button confirmButton = new Button
            {
                Text = "确认保存",
                Location = new Point(950, 10),
                Size = new Size(80, 30),
                DialogResult = DialogResult.OK,
                BackColor = Color.FromArgb(76, 175, 80),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };
            
            buttonPanel.Controls.Add(confirmButton);

            // 取消按钮
            Button cancelButton = new Button
            {
                Text = "取消",
                Location = new Point(1050, 10),
                Size = new Size(80, 30),
                DialogResult = DialogResult.Cancel,
                BackColor = Color.FromArgb(244, 67, 54),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };
            buttonPanel.Controls.Add(cancelButton);

            previewForm.Controls.Add(buttonPanel);
            previewForm.AcceptButton = confirmButton;
            previewForm.CancelButton = cancelButton;

            // 显示对话框并返回结果
            return previewForm.ShowDialog();
        }

        /// <summary>
        /// 显示JSON编辑对话框
        /// </summary>
        /// <param name="jsonContent">JSON内容</param>
        /// <param name="jsonFilePath">JSON文件路径</param>
        /// <returns>用户的选择结果</returns>
        private DialogResult ShowJsonEditDialog(string jsonContent, string jsonFilePath)
        {
            // 创建JSON编辑窗体
            Form editForm = new Form
            {
                Text = $"编辑JSON文件 - {Path.GetFileName(jsonFilePath)}",
                Size = new Size(2000, 1200),
                StartPosition = FormStartPosition.CenterParent,
                FormBorderStyle = FormBorderStyle.Sizable,
                MaximizeBox = true,
                MinimizeBox = true,
                MinimumSize = new Size(2000, 1200)
            };

            // 创建主容器
            Panel mainContainer = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.White
            };

            // 左侧面板 - 原始内容
            Panel leftPanel = new Panel
            {
                Location = new Point(10, 10),
                Size = new Size(980, 1200),
                BackColor = Color.White,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left
            };

            Label originalLabel = new Label
            {
                Text = "原始内容:",
                Location = new Point(10, 10),
                Size = new Size(200, 20),
                Font = new Font("Microsoft YaHei", 10, FontStyle.Bold),
                ForeColor = Color.FromArgb(51, 51, 51),
                TabStop = false
            };
            leftPanel.Controls.Add(originalLabel);

            RichTextBox originalTextBox = new RichTextBox
            {
                Location = new Point(10, 35),
                Size = new Size(960, 1155),
                Font = new Font("Consolas", 10),
                ReadOnly = true,
                BackColor = Color.FromArgb(248, 249, 250),
                BorderStyle = BorderStyle.FixedSingle,
                ScrollBars = RichTextBoxScrollBars.Both,
                WordWrap = false,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                TabStop = false,
                MaxLength = 0 // 无限制长度
            };

            // 为原始内容文本框添加鼠标滚轮事件处理，确保滚动功能正常
            originalTextBox.MouseWheel += (sender, e) => {
                try
                {
                    // 确保鼠标滚轮事件能正常处理
                    if (e.Delta != 0)
                    {
                        // 鼠标滚轮事件正常，不需要特殊处理
                        // RichTextBox会自动处理滚动
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"鼠标滚轮事件处理出错: {ex.Message}");
                }
            };
            originalTextBox.Text = jsonContent;
            leftPanel.Controls.Add(originalTextBox);

            // 右侧面板 - 编辑内容
            Panel rightPanel = new Panel
            {
                Location = new Point(1000, 10),
                Size = new Size(980, 1200),
                BackColor = Color.White,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            Label editLabel = new Label
            {
                Text = "编辑内容:",
                Location = new Point(10, 10),
                Size = new Size(200, 20),
                Font = new Font("Microsoft YaHei", 10, FontStyle.Bold),
                ForeColor = Color.FromArgb(51, 51, 51),
                TabStop = false
            };
            rightPanel.Controls.Add(editLabel);

            // 状态标签
            Label statusLabel = new Label
            {
                Text = "状态: 准备就绪",
                Location = new Point(220, 10),
                Size = new Size(300, 20),
                Font = new Font("Microsoft YaHei", 9),
                ForeColor = Color.FromArgb(100, 100, 100),
                TabStop = false
            };
            rightPanel.Controls.Add(statusLabel);

            // 自动对比开关
            CheckBox autoCompareCheckBox = new CheckBox
            {
                Text = "自动对比",
                Location = new Point(530, 10),
                Size = new Size(80, 20),
                Checked = true,
                TabStop = false
            };
            rightPanel.Controls.Add(autoCompareCheckBox);

            RichTextBox editTextBox = new RichTextBox
            {
                Location = new Point(10, 35),
                Size = new Size(960, 1155),
                Font = new Font("Consolas", 10),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                ScrollBars = RichTextBoxScrollBars.Both,
                WordWrap = false,
                AcceptsTab = true,
                Text = jsonContent,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                TabIndex = 0,
                Enabled = true,
                MaxLength = 0 // 无限制长度
            };

            // 为编辑文本框添加鼠标滚轮事件处理，确保滚动功能正常
            editTextBox.MouseWheel += (sender, e) => {
                try
                {
                    // 确保鼠标滚轮事件能正常处理
                    if (e.Delta != 0)
                    {
                        // 鼠标滚轮事件正常，不需要特殊处理
                        // RichTextBox会自动处理滚动
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"鼠标滚轮事件处理出错: {ex.Message}");
                }
            };

            // 添加文本变化事件，自动对比
            System.Windows.Forms.Timer autoCompareTimer = new System.Windows.Forms.Timer
            {
                Interval = 3000 // 3秒延迟，进一步减少频繁对比
            };
            autoCompareTimer.Tick += (sender, e) => {
                autoCompareTimer.Stop();
                
                // 只有在自动对比启用时才执行
                if (!autoCompareCheckBox.Checked)
                    return;
                    
                try
                {
                    // 保存当前光标位置
                    int currentSelectionStart = editTextBox.SelectionStart;
                    int currentSelectionLength = editTextBox.SelectionLength;

                    // 验证JSON格式
                    string errorMessage;
                    if (ValidateJsonFormatWithDetails(editTextBox.Text, out errorMessage))
                    {
                        // 检查内容是否真的发生了变化
                        var originalJson = Newtonsoft.Json.Linq.JToken.Parse(originalTextBox.Text);
                        var modifiedJson = Newtonsoft.Json.Linq.JToken.Parse(editTextBox.Text);

                        List<string> changedPaths = new List<string>();
                        FindChangedLeafPaths(originalJson, modifiedJson, "", changedPaths);

                        // 只有当变化数量改变时才重新高亮
                        string currentStatus = statusLabel.Text;
                        string newStatus = changedPaths.Count > 0 ? $"状态: 发现 {changedPaths.Count} 处变化" : "状态: 无变化";
                        
                        if (currentStatus != newStatus)
                        {
                            // 清除之前的高亮
                            originalTextBox.SelectAll();
                            originalTextBox.SelectionBackColor = originalTextBox.BackColor;
                            originalTextBox.SelectionColor = originalTextBox.ForeColor;
                            originalTextBox.DeselectAll();

                            editTextBox.SelectAll();
                            editTextBox.SelectionBackColor = editTextBox.BackColor;
                            editTextBox.SelectionColor = editTextBox.ForeColor;
                            editTextBox.DeselectAll();

                            // 应用新的高亮
                            foreach (string path in changedPaths)
                            {
                                HighlightJsonValueOnlyValue(originalTextBox, path, new List<int>(), new List<int>());
                                HighlightJsonValueOnlyValue(editTextBox, path, new List<int>(), new List<int>());
                            }
                        }

                        // 恢复光标位置
                        if (currentSelectionStart <= editTextBox.TextLength)
                        {
                            editTextBox.SelectionStart = currentSelectionStart;
                            editTextBox.SelectionLength = currentSelectionLength;
                        }

                        // 更新状态标签
                        if (changedPaths.Count > 0)
                        {
                            statusLabel.Text = $"状态: 发现 {changedPaths.Count} 处变化";
                            statusLabel.ForeColor = Color.FromArgb(255, 152, 0);
                        }
                        else
                        {
                            statusLabel.Text = "状态: 无变化";
                            statusLabel.ForeColor = Color.FromArgb(76, 175, 80);
                        }
                    }
                    else
                    {
                        // 恢复光标位置
                        if (currentSelectionStart <= editTextBox.TextLength)
                        {
                            editTextBox.SelectionStart = currentSelectionStart;
                            editTextBox.SelectionLength = currentSelectionLength;
                        }
                        statusLabel.Text = "状态: JSON格式错误";
                        statusLabel.ForeColor = Color.FromArgb(244, 67, 54);
                    }
                }
                catch
                {
                    // JSON格式错误时不进行对比
                    statusLabel.Text = "状态: JSON格式错误";
                    statusLabel.ForeColor = Color.FromArgb(244, 67, 54);
                }
            };

            editTextBox.TextChanged += (sender, e) => {
                // 只有在用户停止输入3秒后才进行对比，且自动对比已启用
                if (autoCompareCheckBox.Checked)
                {
                    autoCompareTimer.Stop();
                    autoCompareTimer.Start();
                }
            };

            // 添加复选框事件处理（在定时器声明之后）
            autoCompareCheckBox.CheckedChanged += (sender, e) => {
                if (!autoCompareCheckBox.Checked)
                {
                    // 取消自动对比时停止定时器
                    autoCompareTimer.Stop();
                    statusLabel.Text = "状态: 自动对比已禁用";
                    statusLabel.ForeColor = Color.FromArgb(100, 100, 100);
                }
                else
                {
                    statusLabel.Text = "状态: 自动对比已启用";
                    statusLabel.ForeColor = Color.FromArgb(76, 175, 80);
                }
            };

            // 添加键盘事件测试
            editTextBox.KeyDown += (sender, e) => {
                // 测试键盘输入是否正常工作
                if (e.KeyCode == Keys.A && e.Control)
                {
                    // Ctrl+A 全选
                    editTextBox.SelectAll();
                }
            };

            rightPanel.Controls.Add(editTextBox);

            // 添加面板到主容器
            mainContainer.Controls.Add(leftPanel);
            mainContainer.Controls.Add(rightPanel);
            editForm.Controls.Add(mainContainer);

            // 设置默认焦点到编辑文本框
            editForm.Load += (sender, e) => {
                try
                {
                    // 尝试最大化窗口以获得最大显示空间
                    try
                    {
                        editForm.WindowState = FormWindowState.Maximized;
                    }
                    catch
                    {
                        // 如果最大化失败，使用大尺寸
                        editForm.Size = new Size(2000, 1200);
                    }
                    
                    // 强制调整文本框大小以获得最大显示空间
                    System.Threading.Thread.Sleep(100); // 等待窗体完全加载
                    
                    // 重新计算并设置文本框大小
                    int availableHeight = editForm.ClientSize.Height - 50; // 减去顶部菜单栏高度
                    int panelWidth = (editForm.ClientSize.Width - 30) / 2; // 左右各一半
                    
                    leftPanel.Size = new Size(panelWidth, availableHeight);
                    rightPanel.Size = new Size(panelWidth, availableHeight);
                    rightPanel.Location = new Point(panelWidth + 20, 10);
                    
                    originalTextBox.Size = new Size(panelWidth - 20, availableHeight - 45);
                    editTextBox.Size = new Size(panelWidth - 20, availableHeight - 45);
                    
                    editTextBox.Focus();
                    
                    // 确保显示完整内容 - 滚动到底部
                    if (editTextBox.TextLength > 0)
                    {
                        // 先滚动到底部
                        editTextBox.SelectionStart = editTextBox.TextLength;
                        editTextBox.ScrollToCaret();
                        
                        // 然后滚动到顶部
                        editTextBox.SelectionStart = 0;
                        editTextBox.ScrollToCaret();
                        
                        // 清除选择
                        editTextBox.SelectionLength = 0;
                    }
                    
                    // 添加调试信息
                    Console.WriteLine($"编辑文本框已创建，控件数量: {rightPanel.Controls.Count}");
                    Console.WriteLine($"JSON内容长度: {editTextBox.TextLength}");
                    Console.WriteLine($"窗体尺寸: {editForm.Size}");
                    Console.WriteLine($"文本框尺寸: {editTextBox.Size}");
                    Console.WriteLine($"左侧面板尺寸: {leftPanel.Size}");
                    Console.WriteLine($"右侧面板尺寸: {rightPanel.Size}");
                    Console.WriteLine($"主容器尺寸: {mainContainer.Size}");
                    Console.WriteLine($"屏幕工作区: {Screen.PrimaryScreen.WorkingArea}");
                    
                    // 显示详细的尺寸信息
                    string sizeInfo = $"窗体尺寸: {editForm.Size}\n" +
                                    $"主容器尺寸: {mainContainer.Size}\n" +
                                    $"左侧面板: {leftPanel.Size}\n" +
                                    $"右侧面板: {rightPanel.Size}\n" +
                                    $"原始文本框: {originalTextBox.Size}\n" +
                                    $"编辑文本框: {editTextBox.Size}\n" +
                                    $"屏幕工作区: {Screen.PrimaryScreen.WorkingArea}";
                    
                    Console.WriteLine(sizeInfo);
                    
                    // 显示内容长度信息
                    if (editTextBox.TextLength > 10000)
                    {
                        MessageBox.Show($"JSON文件较大，共 {editTextBox.TextLength} 个字符。\n\n窗体已最大化，文本框高度为 {editTextBox.Height} 像素。\n\n详细尺寸信息：\n窗体: {editForm.Size}\n文本框: {editTextBox.Size}\n屏幕: {Screen.PrimaryScreen.WorkingArea}\n\n如果仍然看不到底部内容，请：\n1. 使用鼠标滚轮滚动\n2. 点击'跳转到底部'按钮\n3. 点击'跳转到位置'按钮\n4. 使用滚动条\n5. 按 Ctrl+End 跳转到底部\n6. 调整窗体大小以获得更多空间", "文件大小提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"设置焦点时出错: {ex.Message}", "调试信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            };

            // 创建顶部菜单栏
            MenuStrip menuStrip = new MenuStrip
            {
                Dock = DockStyle.Top,
                BackColor = Color.FromArgb(51, 51, 51),
                ForeColor = Color.White,
                Font = new Font("Microsoft YaHei", 9),
                RenderMode = ToolStripRenderMode.Professional
            };

            // 文件菜单
            ToolStripMenuItem fileMenu = new ToolStripMenuItem("文件(&F)");
            
            // 保存菜单项
            ToolStripMenuItem saveMenuItem = new ToolStripMenuItem("💾 保存(&S)", null, (sender, e) => {
                // 验证JSON格式
                string errorMessage;
                if (!ValidateJsonFormatWithDetails(editTextBox.Text, out errorMessage))
                {
                    MessageBox.Show($"JSON格式错误，无法保存：\n{errorMessage}", "JSON格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                try
                {
                    // 保存到文件
                    File.WriteAllText(jsonFilePath, editTextBox.Text, new System.Text.UTF8Encoding(false));
                    editForm.DialogResult = DialogResult.OK;
                    editForm.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存文件时出错：{ex.Message}", "保存错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    // 保存失败时，重新聚焦到编辑文本框
                    editTextBox.Focus();
                }
            });
            fileMenu.DropDownItems.Add(saveMenuItem);
            
            // 退出菜单项
            ToolStripMenuItem exitMenuItem = new ToolStripMenuItem("❌ 退出(&X)", null, (sender, e) => {
                editForm.DialogResult = DialogResult.Cancel;
                editForm.Close();
            });
            fileMenu.DropDownItems.Add(exitMenuItem);
            
            menuStrip.Items.Add(fileMenu);

            // 编辑菜单
            ToolStripMenuItem editMenu = new ToolStripMenuItem("编辑(&E)");
            
            // 对比变化菜单项
            ToolStripMenuItem compareMenuItem = new ToolStripMenuItem("🔍 对比变化(&C)", null, (sender, e) => {
                try
                {
                    // 保存当前光标位置
                    int currentSelectionStart = editTextBox.SelectionStart;
                    int currentSelectionLength = editTextBox.SelectionLength;

                    // 验证编辑后的JSON格式
                    string errorMessage;
                    if (!ValidateJsonFormatWithDetails(editTextBox.Text, out errorMessage))
                    {
                        MessageBox.Show($"JSON格式错误，无法对比：\n{errorMessage}", "JSON格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    // 执行对比和高亮
                    ShowJsonComparison(originalTextBox, originalTextBox.Text, editTextBox, editTextBox.Text);

                    // 恢复光标位置
                    if (currentSelectionStart <= editTextBox.TextLength)
                    {
                        editTextBox.SelectionStart = currentSelectionStart;
                        editTextBox.SelectionLength = currentSelectionLength;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"对比时出现错误：{ex.Message}", "对比错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });
            editMenu.DropDownItems.Add(compareMenuItem);
            
            // 清除高亮菜单项
            ToolStripMenuItem clearHighlightMenuItem = new ToolStripMenuItem("🧹 清除高亮(&H)", null, (sender, e) => {
                // 保存当前光标位置
                int currentSelectionStart = editTextBox.SelectionStart;
                int currentSelectionLength = editTextBox.SelectionLength;

                // 清除所有高亮
                originalTextBox.SelectAll();
                originalTextBox.SelectionBackColor = originalTextBox.BackColor;
                originalTextBox.SelectionColor = originalTextBox.ForeColor;
                originalTextBox.DeselectAll();

                editTextBox.SelectAll();
                editTextBox.SelectionBackColor = editTextBox.BackColor;
                editTextBox.SelectionColor = editTextBox.ForeColor;
                editTextBox.DeselectAll();

                // 恢复光标位置
                if (currentSelectionStart <= editTextBox.TextLength)
                {
                    editTextBox.SelectionStart = currentSelectionStart;
                    editTextBox.SelectionLength = currentSelectionLength;
                }

                statusLabel.Text = "状态: 已清除高亮";
                statusLabel.ForeColor = Color.FromArgb(100, 100, 100);
            });
            editMenu.DropDownItems.Add(clearHighlightMenuItem);
            
            menuStrip.Items.Add(editMenu);

            // 工具菜单
            ToolStripMenuItem toolsMenu = new ToolStripMenuItem("工具(&T)");
            
            // 验证格式菜单项
            ToolStripMenuItem validateMenuItem = new ToolStripMenuItem("✅ 验证格式(&V)", null, (sender, e) => {
                string errorMessage;
                if (ValidateJsonFormatWithDetails(editTextBox.Text, out errorMessage))
                {
                    MessageBox.Show("JSON格式验证通过", "验证成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show($"JSON格式验证失败：\n{errorMessage}", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });
            toolsMenu.DropDownItems.Add(validateMenuItem);
            
            menuStrip.Items.Add(toolsMenu);

            // 导航菜单
            ToolStripMenuItem navigateMenu = new ToolStripMenuItem("导航(&N)");
            
            // 跳转到顶部菜单项
            ToolStripMenuItem gotoTopMenuItem = new ToolStripMenuItem("⬆️ 跳转到顶部(&T)", null, (sender, e) => {
                try
                {
                    // 保存当前光标位置
                    int currentSelectionStart = editTextBox.SelectionStart;
                    int currentSelectionLength = editTextBox.SelectionLength;
                    
                    // 跳转到顶部
                    editTextBox.SelectionStart = 0;
                    editTextBox.ScrollToCaret();
                    
                    // 恢复光标位置
                    editTextBox.SelectionStart = currentSelectionStart;
                    editTextBox.SelectionLength = currentSelectionLength;
                    
                    MessageBox.Show("已跳转到JSON内容顶部", "跳转完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"跳转时出错: {ex.Message}", "跳转错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });
            navigateMenu.DropDownItems.Add(gotoTopMenuItem);
            
            // 跳转到底部菜单项
            ToolStripMenuItem gotoBottomMenuItem = new ToolStripMenuItem("⬇️ 跳转到底部(&B)", null, (sender, e) => {
                try
                {
                    // 保存当前光标位置
                    int currentSelectionStart = editTextBox.SelectionStart;
                    int currentSelectionLength = editTextBox.SelectionLength;
                    
                    // 跳转到底部
                    editTextBox.SelectionStart = editTextBox.TextLength;
                    editTextBox.ScrollToCaret();
                    
                    // 恢复光标位置
                    editTextBox.SelectionStart = currentSelectionStart;
                    editTextBox.SelectionLength = currentSelectionLength;
                    
                    MessageBox.Show("已跳转到JSON内容底部", "跳转完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"跳转时出错: {ex.Message}", "跳转错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });
            navigateMenu.DropDownItems.Add(gotoBottomMenuItem);
            
            // 跳转到指定位置菜单项
            ToolStripMenuItem gotoPositionMenuItem = new ToolStripMenuItem("🎯 跳转到位置(&P)", null, (sender, e) => {
                try
                {
                    // 显示输入对话框
                    string input = Microsoft.VisualBasic.Interaction.InputBox(
                        "请输入跳转位置：\n\n" +
                        "1. 输入百分比 (如: 50 表示50%)\n" +
                        "2. 输入行号 (如: 100 表示第100行)\n" +
                        "3. 输入字符位置 (如: 5000 表示第5000个字符)\n\n" +
                        "当前JSON总长度: " + editTextBox.TextLength + " 字符",
                        "跳转到指定位置",
                        "50");

                    if (!string.IsNullOrEmpty(input))
                    {
                        int position = 0;
                        
                        if (input.EndsWith("%"))
                        {
                            // 百分比跳转
                            if (int.TryParse(input.TrimEnd('%'), out int percent))
                            {
                                position = (int)(editTextBox.TextLength * percent / 100.0);
                            }
                        }
                        else if (int.TryParse(input, out int value))
                        {
                            if (value <= 1000)
                            {
                                // 假设是行号，每行平均50个字符
                                position = Math.Min(editTextBox.TextLength, value * 50);
                            }
                            else
                            {
                                // 假设是字符位置
                                position = Math.Min(editTextBox.TextLength, value);
                            }
                        }

                        if (position > 0)
                        {
                            // 保存当前光标位置
                            int currentSelectionStart = editTextBox.SelectionStart;
                            int currentSelectionLength = editTextBox.SelectionLength;
                            
                            // 跳转到指定位置
                            editTextBox.SelectionStart = position;
                            editTextBox.ScrollToCaret();
                            
                            // 恢复光标位置
                            editTextBox.SelectionStart = currentSelectionStart;
                            editTextBox.SelectionLength = currentSelectionLength;
                            
                            MessageBox.Show($"已跳转到位置 {position} (总长度: {editTextBox.TextLength})", "跳转完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"跳转时出错: {ex.Message}", "跳转错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });
            navigateMenu.DropDownItems.Add(gotoPositionMenuItem);
            
            menuStrip.Items.Add(navigateMenu);

            // 添加菜单栏到窗体
            editForm.Controls.Add(menuStrip);
            editForm.MainMenuStrip = menuStrip;
            
            // 添加窗体大小改变事件，自动调整文本框大小
            editForm.Resize += (sender, e) => {
                try
                {
                    // 重新计算并设置文本框大小
                    int availableHeight = editForm.ClientSize.Height - 50; // 减去顶部菜单栏高度
                    int panelWidth = (editForm.ClientSize.Width - 30) / 2; // 左右各一半
                    
                    leftPanel.Size = new Size(panelWidth, availableHeight);
                    rightPanel.Size = new Size(panelWidth, availableHeight);
                    rightPanel.Location = new Point(panelWidth + 20, 10);
                    
                    originalTextBox.Size = new Size(panelWidth - 20, availableHeight - 45);
                    editTextBox.Size = new Size(panelWidth - 20, availableHeight - 45);
                    
                    Console.WriteLine($"窗体大小改变 - 新尺寸: {editForm.Size}, 文本框尺寸: {editTextBox.Size}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"调整大小时出错: {ex.Message}");
                }
            };

            // 显示对话框并返回结果
            return editForm.ShowDialog();
        }

        /// <summary>
        /// 显示JSON对比和高亮
        /// </summary>
        /// <param name="originalTextBox">原始内容文本框</param>
        /// <param name="originalContent">原始内容</param>
        /// <param name="modifiedTextBox">修改后内容文本框</param>
        /// <param name="modifiedContent">修改后内容</param>
        private void ShowJsonComparison(RichTextBox originalTextBox, string originalContent, RichTextBox modifiedTextBox, string modifiedContent)
        {
            try
            {
                // 保存当前光标位置
                int currentSelectionStart = modifiedTextBox.SelectionStart;
                int currentSelectionLength = modifiedTextBox.SelectionLength;

                // 解析JSON
                var originalJson = Newtonsoft.Json.Linq.JToken.Parse(originalContent);
                var modifiedJson = Newtonsoft.Json.Linq.JToken.Parse(modifiedContent);

                // 查找变化的路径
                List<string> changedPaths = new List<string>();
                FindChangedLeafPaths(originalJson, modifiedJson, "", changedPaths);

                // 清除之前的高亮
                originalTextBox.SelectAll();
                originalTextBox.SelectionBackColor = originalTextBox.BackColor;
                originalTextBox.SelectionColor = originalTextBox.ForeColor;
                originalTextBox.DeselectAll();

                modifiedTextBox.SelectAll();
                modifiedTextBox.SelectionBackColor = modifiedTextBox.BackColor;
                modifiedTextBox.SelectionColor = modifiedTextBox.ForeColor;
                modifiedTextBox.DeselectAll();

                // 高亮显示变化
                foreach (string path in changedPaths)
                {
                    HighlightJsonValueOnlyValue(originalTextBox, path, new List<int>(), new List<int>());
                    HighlightJsonValueOnlyValue(modifiedTextBox, path, new List<int>(), new List<int>());
                }

                // 恢复光标位置
                if (currentSelectionStart <= modifiedTextBox.TextLength)
                {
                    modifiedTextBox.SelectionStart = currentSelectionStart;
                    modifiedTextBox.SelectionLength = currentSelectionLength;
                }

                // 显示变化统计
                string changeInfo = $"发现 {changedPaths.Count} 处变化";
                if (changedPaths.Count > 0)
                {
                    changeInfo += "\n变化路径:\n" + string.Join("\n", changedPaths.Take(10));
                    if (changedPaths.Count > 10)
                    {
                        changeInfo += $"\n... 还有 {changedPaths.Count - 10} 处变化";
                    }
                }

                MessageBox.Show(changeInfo, "对比结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"对比过程中出现错误：{ex.Message}", "对比错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 设置JSON文本并高亮差异
        /// </summary>
        /// <param name="originalTextBox">原始文本框</param>
        /// <param name="originalContent">原始内容</param>
        /// <param name="modifiedTextBox">修改后文本框</param>
        /// <param name="modifiedContent">修改后内容</param>
        private void SetJsonWithHighlights(RichTextBox originalTextBox, string originalContent, RichTextBox modifiedTextBox, string modifiedContent, List<int> highlightStarts, List<int> highlightLengths)
        {
            // 设置原始内容
            originalTextBox.Text = originalContent;
            originalTextBox.SelectAll();
            originalTextBox.SelectionColor = Color.FromArgb(73, 80, 87); // 灰色
            originalTextBox.DeselectAll();

            // 设置修改后内容
            modifiedTextBox.Text = modifiedContent;
            modifiedTextBox.SelectAll();
            modifiedTextBox.SelectionColor = Color.FromArgb(73, 80, 87); // 绿色
            modifiedTextBox.DeselectAll();

            if (string.IsNullOrEmpty(originalContent))
            {
                originalTextBox.Text = "// 无原始数据可对比";
                originalTextBox.SelectAll();
                originalTextBox.SelectionColor = Color.FromArgb(108, 117, 125); // 浅灰色
                originalTextBox.DeselectAll();
            }

            // 高亮显示修改的部分，并收集高亮位置
            HighlightDifferences(originalTextBox, modifiedTextBox, highlightStarts, highlightLengths);
        }

        /// <summary>
        /// 高亮显示JSON差异
        /// </summary>
        /// <param name="originalTextBox">原始文本框</param>
        /// <param name="modifiedTextBox">修改后文本框</param>
        private void HighlightDifferences(RichTextBox originalTextBox, RichTextBox modifiedTextBox, List<int> highlightStarts, List<int> highlightLengths)
        {
            try
            {
                var originalJson = Newtonsoft.Json.Linq.JToken.Parse(originalTextBox.Text);
                var modifiedJson = Newtonsoft.Json.Linq.JToken.Parse(modifiedTextBox.Text);
                if (originalJson == null || modifiedJson == null) return;

                var changedPaths = new List<string>();
                FindChangedLeafPaths(originalJson, modifiedJson, "", changedPaths);

                foreach (var path in changedPaths)
                {
                    HighlightJsonValueOnlyValue(modifiedTextBox, path, highlightStarts, highlightLengths);
                }
            }
            catch { }
        }

        // 递归找出所有发生变化的叶子节点路径
        private void FindChangedLeafPaths(Newtonsoft.Json.Linq.JToken orig, Newtonsoft.Json.Linq.JToken mod, string path, List<string> changedPaths)
        {
            if (orig == null && mod != null)
            {
                // 新增
                // 对于新增的属性，添加整个路径，而不仅仅是叶子节点
                if (mod is Newtonsoft.Json.Linq.JValue)
                {
                    // 对于简单值，添加整个属性路径
                    changedPaths.Add(path);
                }
                else
                {
                    // 对于复杂对象，收集所有叶子节点路径
                    CollectAllLeafPaths(mod, path, changedPaths);
                }
                return;
            }
            if (orig != null && mod == null)
            {
                // 删除
                CollectAllLeafPaths(orig, path, changedPaths);
                return;
            }
            if (orig == null && mod == null) return;

            if (orig.Type != mod.Type)
            {
                CollectAllLeafPaths(mod, path, changedPaths);
                return;
            }

            if (orig is Newtonsoft.Json.Linq.JValue && mod is Newtonsoft.Json.Linq.JValue)
            {
                if (!Newtonsoft.Json.Linq.JToken.DeepEquals(orig, mod))
                {
                    changedPaths.Add(path);
                }
                return;
            }
            if (orig is Newtonsoft.Json.Linq.JObject oObj && mod is Newtonsoft.Json.Linq.JObject mObj)
            {
                var allKeys = oObj.Properties().Select(p => p.Name).Union(mObj.Properties().Select(p => p.Name));
                foreach (var key in allKeys)
                {
                    var oVal = oObj.Property(key)?.Value;
                    var mVal = mObj.Property(key)?.Value;
                    FindChangedLeafPaths(oVal, mVal, path == "" ? key : path + "." + key, changedPaths);
                }
                return;
            }
            if (orig is Newtonsoft.Json.Linq.JArray oArr && mod is Newtonsoft.Json.Linq.JArray mArr)
            {
                int maxLen = Math.Max(oArr.Count, mArr.Count);
                for (int i = 0; i < maxLen; i++)
                {
                    var oVal = i < oArr.Count ? oArr[i] : null;
                    var mVal = i < mArr.Count ? mArr[i] : null;
                    
                    // 如果是新增的数组项（原始为null，修改后有值）
                    if (oVal == null && mVal != null)
                    {
                        // 对于新增的复杂对象，添加整个路径
                        if (mVal is Newtonsoft.Json.Linq.JObject)
                        {
                            changedPaths.Add(path + "[" + i + "]");
                        }
                        else
                        {
                            // 对于简单值，收集所有叶子节点
                            CollectAllLeafPaths(mVal, path + "[" + i + "]", changedPaths);
                        }
                    }
                    else
                    {
                        // 递归比较现有项
                        FindChangedLeafPaths(oVal, mVal, path + "[" + i + "]", changedPaths);
                    }
                }
                return;
            }
        }

        // 收集所有叶子节点路径
        private void CollectAllLeafPaths(Newtonsoft.Json.Linq.JToken token, string path, List<string> paths)
        {
            if (token is Newtonsoft.Json.Linq.JValue)
            {
                paths.Add(path);
                return;
            }
            if (token is Newtonsoft.Json.Linq.JObject obj)
            {
                // 对于复杂对象，如果路径包含数组索引，添加整个对象路径
                if (path.Contains("["))
                {
                    paths.Add(path);
                }
                else
                {
                    // 否则收集所有属性路径
                    foreach (var prop in obj.Properties())
                    {
                        CollectAllLeafPaths(prop.Value, path == "" ? prop.Name : path + "." + prop.Name, paths);
                    }
                }
                return;
            }
            if (token is Newtonsoft.Json.Linq.JArray arr)
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    CollectAllLeafPaths(arr[i], path + "[" + i + "]", paths);
                }
                return;
            }
        }

        // 高亮JSON值（支持路径，包括新增的复杂对象）
        private void HighlightJsonValueOnlyValue(RichTextBox textBox, string path, List<int> highlightStarts, List<int> highlightLengths)
        {
            string[] parts = path.Split('.');
            int searchIndex = 0;
            int valueStart = -1, valueEnd = -1;
            int propertyStart = -1; // 属性开始位置（包括属性名）
            string fullText = textBox.Text;
            
            // 检查是否是数组索引路径（新增的List<Class>项）
            bool isArrayIndexPath = false;
            int arrayIndex = -1;
            string arrayKey = "";
            
            for (int i = 0; i < parts.Length; i++)
            {
                string part = parts[i];
                string key = part;
                int arrIdx = -1;
                if (part.Contains("["))
                {
                    int idx1 = part.IndexOf('[');
                    key = part.Substring(0, idx1);
                    arrIdx = int.Parse(part.Substring(idx1 + 1, part.IndexOf(']') - idx1 - 1));
                    
                    // 检查是否是新增的数组项
                    if (i == parts.Length - 1)
                    {
                        isArrayIndexPath = true;
                        arrayIndex = arrIdx;
                        arrayKey = key;
                    }
                }
                
                string searchPattern = $"\"{key}\":";
                searchIndex = fullText.IndexOf(searchPattern, searchIndex);
                if (searchIndex < 0) return;
                
                // 记录属性开始位置（包括属性名）
                if (i == parts.Length - 1)
                {
                    propertyStart = searchIndex;
                }
                
                valueStart = fullText.IndexOf(':', searchIndex) + 1;
                while (valueStart < fullText.Length && char.IsWhiteSpace(fullText[valueStart])) valueStart++;
                
                if (arrIdx >= 0)
                {
                    int arrStart = fullText.IndexOf('[', valueStart);
                    if (arrStart < 0) return;
                    int arrElemStart = arrStart + 1;
                    for (int j = 0; j <= arrIdx; j++)
                    {
                        arrElemStart = SkipWhitespace(fullText, arrElemStart);
                        int arrElemEnd = FindJsonValueEnd(fullText, arrElemStart);
                        if (j == arrIdx)
                        {
                            valueStart = arrElemStart;
                            valueEnd = arrElemEnd;
                            break;
                        }
                        arrElemStart = arrElemEnd;
                        if (arrElemStart < fullText.Length && fullText[arrElemStart] == ',') arrElemStart++;
                    }
                }
                else if (i == parts.Length - 1)
                {
                    valueEnd = FindJsonValueEnd(fullText, valueStart);
                }
                else
                {
                    searchIndex = fullText.IndexOf('{', valueStart);
                    if (searchIndex < 0) return;
                    searchIndex++;
                }
            }
            
            if (valueStart >= 0 && valueEnd > valueStart)
            {
                // 如果是新增的数组项，高亮整个对象结构
                if (isArrayIndexPath)
                {
                    // 检查是否是复杂对象（以{开头）
                    string valueContent = fullText.Substring(valueStart, valueEnd - valueStart).Trim();
                    if (valueContent.StartsWith("{"))
                    {
                        // 高亮整个对象，包括属性名和值
                        textBox.Select(valueStart, valueEnd - valueStart);
                        textBox.SelectionBackColor = Color.FromArgb(255, 193, 7);
                        textBox.SelectionColor = Color.Black;
                        textBox.DeselectAll();
                        highlightStarts.Add(valueStart);
                        highlightLengths.Add(valueEnd - valueStart);
                    }
                    else
                    {
                        // 简单值，只高亮值部分
                        textBox.Select(valueStart, valueEnd - valueStart);
                        textBox.SelectionBackColor = Color.FromArgb(255, 193, 7);
                        textBox.SelectionColor = Color.Black;
                        textBox.DeselectAll();
                        highlightStarts.Add(valueStart);
                        highlightLengths.Add(valueEnd - valueStart);
                    }
                }
                else
                {
                    // 检查是否是新增的属性（路径中没有数组索引）
                    bool isNewProperty = !path.Contains("[");
                    
                    if (isNewProperty && propertyStart >= 0)
                    {
                        // 对于新增的属性，高亮整个属性（包括属性名和值）
                        textBox.Select(propertyStart, valueEnd - propertyStart);
                        textBox.SelectionBackColor = Color.FromArgb(255, 193, 7);
                        textBox.SelectionColor = Color.Black;
                        textBox.DeselectAll();
                        highlightStarts.Add(propertyStart);
                        highlightLengths.Add(valueEnd - propertyStart);
                    }
                    else
                    {
                        // 普通路径，只高亮值部分
                        textBox.Select(valueStart, valueEnd - valueStart);
                        textBox.SelectionBackColor = Color.FromArgb(255, 193, 7);
                        textBox.SelectionColor = Color.Black;
                        textBox.DeselectAll();
                        highlightStarts.Add(valueStart);
                        highlightLengths.Add(valueEnd - valueStart);
                    }
                }
            }
        }
        private int SkipWhitespace(string text, int idx)
        {
            while (idx < text.Length && char.IsWhiteSpace(text[idx])) idx++;
            return idx;
        }

        /// <summary>
        /// 查找JSON值的结束位置
        /// </summary>
        /// <param name="text">文本</param>
        /// <param name="startIndex">开始位置</param>
        /// <returns>结束位置</returns>
        private int FindJsonValueEnd(string text, int startIndex)
        {
            int index = startIndex;
            int braceCount = 0;
            int bracketCount = 0;
            bool inString = false;
            bool escaped = false;

            while (index < text.Length)
            {
                char c = text[index];

                if (escaped)
                {
                    escaped = false;
                    index++;
                    continue;
                }

                if (c == '\\')
                {
                    escaped = true;
                    index++;
                    continue;
                }

                if (c == '"' && !escaped)
                {
                    inString = !inString;
                    index++;
                    continue;
                }

                if (!inString)
                {
                    if (c == '{')
                    {
                        braceCount++;
                    }
                    else if (c == '}')
                    {
                        braceCount--;
                        if (braceCount < 0) break;
                    }
                    else if (c == '[')
                    {
                        bracketCount++;
                    }
                    else if (c == ']')
                    {
                        bracketCount--;
                        if (bracketCount < 0) break;
                    }
                    else if (c == ',' && braceCount == 0 && bracketCount == 0)
                    {
                        // 找到下一个键值对的分隔符
                        break;
                    }
                    else if (c == '\n' && braceCount == 0 && bracketCount == 0)
                    {
                        // 找到换行符，可能是下一个键值对
                        break;
                    }
                }

                index++;
            }

            return index;
        }

        private void UpdateInstanceFromForm(object instance, string prefix = "")
        {
            var properties = instance.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var property in properties)
            {
                string path = string.IsNullOrEmpty(prefix) ? property.Name : $"{prefix}.{property.Name}";

                // 检查是否是泛型集合类型
                bool isGenericList = property.PropertyType.IsGenericType && 
                    (property.PropertyType.GetGenericTypeDefinition() == typeof(List<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>));

                // 判断是否是基本类型的集合
                bool isPrimitiveTypeList = false;
                Type elementType = null;
                
                if (isGenericList)
                {
                    elementType = property.PropertyType.GetGenericArguments()[0];
                    isPrimitiveTypeList = elementType.IsPrimitive || 
                                         elementType == typeof(string) || 
                                         elementType == typeof(decimal) || 
                                         elementType == typeof(DateTime);
                }

                if ((property.PropertyType.IsClass &&
                    property.PropertyType != typeof(string) &&
                    !property.PropertyType.IsArray &&
                    !typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) ||
                    isGenericList)
                {
                    // 获取属性值
                    var nestedObj = property.GetValue(instance);
                    if (nestedObj == null)
                    {
                        try
                        {
                            nestedObj = Activator.CreateInstance(property.PropertyType);
                            property.SetValue(instance, nestedObj);
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    // 处理泛型集合
                    if (isGenericList)
                    {
                        // 对于基本类型的集合，从文本框中解析值
                        if (isPrimitiveTypeList && formControls.TryGetValue(path, out var control) && control is TextBox textBox)
                        {
                            try
                            {
                                // 获取集合实例
                                IList collection = (IList)nestedObj;
                                
                                // 清空现有集合
                                collection.Clear();
                                
                                // 解析文本框内容
                                string[] parts = textBox.Text.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                
                                // 添加每个值到集合
                                foreach (string part in parts)
                                {
                                    object value = ConvertStringToType(part.Trim(), elementType);
                                    if (value != null)
                                    {
                                        collection.Add(value);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception($"解析集合 {property.Name} 时出错: {ex.Message}", ex);
                            }
                        }
                        else
                        {
                            // 对于复杂类型的集合，递归更新每个项
                            IList collection = (IList)nestedObj;
                            
                            // 更新集合中的每个项
                            for (int i = 0; i < collection.Count; i++)
                            {
                                var item = collection[i];
                                UpdateInstanceFromForm(item, $"{path}[{i}]");
                            }
                        }
                    }
                    else
                    {
                        // 递归更新嵌套对象
                        UpdateInstanceFromForm(nestedObj, path);
                    }
                }
                else if (formControls.TryGetValue(path, out var control))
                {
                    // 更新基本属性
                    try
                    {
                        object value = GetControlValue(control, property.PropertyType);
                        property.SetValue(instance, value);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"设置属性 {property.Name} 时出错: {ex.Message}", ex);
                    }
                }
            }
        }

        // 将字符串转换为指定类型的值
        private object ConvertStringToType(string input, Type targetType)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(input))
                    return null;
                    
                if (targetType == typeof(string))
                    return input;
                    
                if (targetType == typeof(int))
                    return int.Parse(input);
                    
                if (targetType == typeof(double))
                    return double.Parse(input);
                    
                if (targetType == typeof(decimal))
                    return decimal.Parse(input);
                    
                if (targetType == typeof(float))
                    return float.Parse(input);
                    
                if (targetType == typeof(bool))
                    return bool.Parse(input);
                    
                if (targetType == typeof(DateTime))
                    return DateTime.Parse(input);
                    
                if (targetType.IsEnum)
                    return Enum.Parse(targetType, input);
                    
                // 其他类型可以根据需要添加
                
                return null;
            }
            catch (Exception ex)
            {
                throw new Exception($"无法将值 \"{input}\" 转换为 {targetType.Name} 类型: {ex.Message}", ex);
            }
        }

        private object GetControlValue(Control control, Type targetType)
        {
            if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                targetType = targetType.GetGenericArguments()[0];
            }

            if (control is TextBox textBox)
            {
                // 处理数组类型
                if (targetType.IsArray)
                {
                    Type elementType = targetType.GetElementType();
                    
                    // 如果数组输入为空，则返回空数组
                    if (string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        // 创建一个指定类型的空数组
                        return Array.CreateInstance(elementType, 0);
                    }
                    
                    // 解析逗号分隔的字符串到数组
                    string[] parts = textBox.Text.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    Array array = Array.CreateInstance(elementType, parts.Length);
                    
                    for (int i = 0; i < parts.Length; i++)
                    {
                        try
                        {
                            if (elementType == typeof(double))
                            {
                                array.SetValue(double.Parse(parts[i].Trim()), i);
                            }
                            else if (elementType == typeof(int))
                            {
                                array.SetValue(int.Parse(parts[i].Trim()), i);
                            }
                            else if (elementType == typeof(decimal))
                            {
                                array.SetValue(decimal.Parse(parts[i].Trim()), i);
                            }
                            else if (elementType == typeof(string))
                            {
                                array.SetValue(parts[i].Trim(), i);
                            }
                            // 可以添加更多类型的解析
                        }
                        catch (FormatException ex)
                        {
                            // 解析失败时抛出异常
                            throw new Exception($"无法将值 \"{parts[i]}\" 转换为 {elementType.Name} 类型", ex);
                        }
                    }
                    return array;
                }

                if (targetType == typeof(string))
                {
                    return textBox.Text;
                }
                else if (targetType == typeof(int))
                {
                    if (!int.TryParse(textBox.Text, out int result))
                    {
                        throw new Exception($"无法将值 \"{textBox.Text}\" 转换为 int 类型");
                    }
                    return result;
                }
                else if (targetType == typeof(decimal))
                {
                    if (!decimal.TryParse(textBox.Text, out decimal result))
                    {
                        throw new Exception($"无法将值 \"{textBox.Text}\" 转换为 decimal 类型");
                    }
                    return result;
                }
                else if (targetType == typeof(double))
                {
                    if (!double.TryParse(textBox.Text, out double result))
                    {
                        throw new Exception($"无法将值 \"{textBox.Text}\" 转换为 double 类型");
                    }
                    return result;
                }
                // 可以添加更多类型转换
            }
            else if (control is NumericUpDown numericUpDown)
            {
                if (targetType == typeof(int))
                {
                    return (int)numericUpDown.Value;
                }
                else if (targetType == typeof(decimal))
                {
                    return numericUpDown.Value;
                }
                else if (targetType == typeof(double))
                {
                    return (double)numericUpDown.Value;
                }
                // 可以添加更多类型转换
            }
            else if (control is CheckBox checkBox)
            {
                return checkBox.Checked;
            }
            else if (control is DateTimePicker dateTimePicker)
            {
                return dateTimePicker.Value;
            }
            else if (control is ComboBox comboBox && comboBox.SelectedItem is ComboBoxItem item)
            {
                return item.Value;
            }

            // 如果无法确定类型，返回null
            return null;
        }

        private void BuildObjectString(object obj, System.Text.StringBuilder builder, string indent = "")
        {
            if (obj == null)
            {
                builder.AppendLine($"{indent}null");
                return;
            }

            Type type = obj.GetType();
            builder.AppendLine($"{indent}{type.Name} {{");

            // 获取所有公共属性
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var property in properties)
            {
                var displayName = property.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? property.Name;
                var value = property.GetValue(obj);

                // 检查是否是泛型集合类型
                bool isGenericList = property.PropertyType.IsGenericType && 
                    (property.PropertyType.GetGenericTypeDefinition() == typeof(List<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>));

                if ((property.PropertyType.IsClass &&
                    property.PropertyType != typeof(string) &&
                    !property.PropertyType.IsArray &&
                    !typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) ||
                    isGenericList)
                {
                    // 对象属性或集合属性
                    builder.AppendLine($"{indent}    {displayName}: ");
                    
                    if (isGenericList && value != null)
                    {
                        // 处理集合类型
                        IList collection = (IList)value;
                        builder.AppendLine($"{indent}    集合 (共{collection.Count}项) {{");
                        
                        for (int i = 0; i < collection.Count; i++)
                        {
                            builder.AppendLine($"{indent}        项目 #{i + 1}:");
                            BuildObjectString(collection[i], builder, indent + "        ");
                        }
                        
                        builder.AppendLine($"{indent}    }}");
                    }
                    else
                    {
                        // 处理普通对象
                        BuildObjectString(value, builder, indent + "    ");
                    }
                }
                else
                {
                    // 基本属性
                    string valueStr = FormatPropertyValue(value);
                    builder.AppendLine($"{indent}    {displayName}: {valueStr}");
                }
            }

            builder.AppendLine($"{indent}}}");
        }

        private string FormatPropertyValue(object value)
        {
            if (value == null)
                return "null";

            if (value is string str)
                return $"\"{str.Replace("\n", "\\n")}\"";

            if (value is DateTime dt)
                return dt.ToString("yyyy-MM-dd");

            if (value is decimal dec)
                return dec.ToString("F2");

            if (value is bool b)
                return b ? "是" : "否";

            if (value is Enum enumValue)
            {
                var enumField = enumValue.GetType().GetField(enumValue.ToString());
                var description = enumField?.GetCustomAttribute<DescriptionAttribute>()?.Description;
                return !string.IsNullOrEmpty(description) ? description : enumValue.ToString();
            }

            return value.ToString();
        }

        private void ShowObjectResult(string result, string title)
        {
            Form resultForm = new Form
            {
                Text = title,
                Size = new Size(500, 400),
                StartPosition = FormStartPosition.CenterParent,
                MinimizeBox = false,
                MaximizeBox = false,
                FormBorderStyle = FormBorderStyle.FixedDialog
            };

            TextBox resultTextBox = new TextBox
            {
                Multiline = true,
                ReadOnly = true,
                ScrollBars = ScrollBars.Both,
                Dock = DockStyle.Fill,
                Font = new Font("Consolas", 10),
                Text = result
            };

            resultForm.Controls.Add(resultTextBox);
            resultForm.ShowDialog();
        }

        /// <summary>
        /// 查找JSON文件，支持相对路径的递归查找
        /// </summary>
        /// <param name="jsonFilePath">JSON文件路径（可以是相对路径或绝对路径）</param>
        /// <returns>找到的完整文件路径，如果找不到则返回null</returns>
        private string FindJsonFile(string jsonFilePath)
        {
            // 如果是绝对路径，直接检查文件是否存在
            if (Path.IsPathRooted(jsonFilePath))
            {
                return File.Exists(jsonFilePath) ? jsonFilePath : null;
            }

            // 搜索路径列表（按优先级排序）
            var searchPaths = new List<string>
            {
                AppDomain.CurrentDomain.BaseDirectory,                    // 应用程序根目录
                Directory.GetCurrentDirectory(),                          // 当前工作目录
                Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory), // 上级目录
                Path.GetDirectoryName(Directory.GetCurrentDirectory())    // 当前工作目录的上级目录
            };

            // 去重并过滤掉null值
            searchPaths = searchPaths.Where(p => !string.IsNullOrEmpty(p)).Distinct().ToList();

            // 在每个路径中搜索JSON文件
            foreach (string searchPath in searchPaths)
            {
                string fullPath = Path.Combine(searchPath, jsonFilePath);
                if (File.Exists(fullPath))
                {
                    return fullPath;
                }
            }

            // 如果直接路径找不到，尝试递归向上查找
            return FindJsonFileRecursive(jsonFilePath, searchPaths);
        }

        /// <summary>
        /// 递归向上查找JSON文件
        /// </summary>
        /// <param name="jsonFilePath">JSON文件路径</param>
        /// <param name="basePaths">基础搜索路径列表</param>
        /// <returns>找到的完整文件路径，如果找不到则返回null</returns>
        private string FindJsonFileRecursive(string jsonFilePath, List<string> basePaths)
        {
            foreach (string basePath in basePaths)
            {
                DirectoryInfo currentDir = new DirectoryInfo(basePath);
                
                // 向上递归查找，最多查找10层目录
                for (int level = 0; level < 10; level++)
                {
                    if (currentDir == null || !currentDir.Exists)
                        break;

                    string fullPath = Path.Combine(currentDir.FullName, jsonFilePath);
                    if (File.Exists(fullPath))
                    {
                        return fullPath;
                    }

                    // 移动到上级目录
                    currentDir = currentDir.Parent;
                }
            }

            return null;
        }

        /// <summary>
        /// 检测文件编码
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>检测到的编码，如果无法检测则返回UTF8</returns>
        private System.Text.Encoding DetectFileEncoding(string filePath)
        {
            try
            {
                byte[] bytes = File.ReadAllBytes(filePath);
                
                // 检查BOM标记
                if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
                {
                    return System.Text.Encoding.UTF8; // UTF-8 with BOM
                }
                else if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE)
                {
                    return System.Text.Encoding.Unicode; // UTF-16 LE
                }
                else if (bytes.Length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF)
                {
                    return System.Text.Encoding.BigEndianUnicode; // UTF-16 BE
                }
                
                // 尝试检测是否为UTF-8（无BOM）
                bool isUtf8 = true;
                for (int i = 0; i < bytes.Length; i++)
                {
                    if (bytes[i] < 0x80)
                    {
                        // ASCII字符，继续
                        continue;
                    }
                    else if (bytes[i] < 0xC0)
                    {
                        // 无效的UTF-8序列
                        isUtf8 = false;
                        break;
                    }
                    else if (bytes[i] < 0xE0)
                    {
                        // 2字节UTF-8序列
                        if (i + 1 >= bytes.Length || (bytes[i + 1] & 0xC0) != 0x80)
                        {
                            isUtf8 = false;
                            break;
                        }
                        i++;
                    }
                    else if (bytes[i] < 0xF0)
                    {
                        // 3字节UTF-8序列
                        if (i + 2 >= bytes.Length || (bytes[i + 1] & 0xC0) != 0x80 || (bytes[i + 2] & 0xC0) != 0x80)
                        {
                            isUtf8 = false;
                            break;
                        }
                        i += 2;
                    }
                    else
                    {
                        isUtf8 = false;
                        break;
                    }
                }
                
                if (isUtf8)
                {
                    return System.Text.Encoding.UTF8;
                }
                
                // 默认返回系统默认编码
                return System.Text.Encoding.Default;
            }
            catch
            {
                // 如果检测失败，返回UTF-8
                return System.Text.Encoding.UTF8;
            }
        }
    }

    // 自定义ComboBox，禁用鼠标滚轮
    public class NoWheelComboBox : ComboBox
    {
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            // 不调用基类方法，从而禁用滚轮功能
            // base.OnMouseWheel(e);
        }

        protected override void WndProc(ref Message m)
        {
            // WM_MOUSEWHEEL = 0x020A
            if (m.Msg == 0x020A)
            {
                // 检查是否在JSON编辑窗口中
                Form parentForm = this.FindForm();
                if (parentForm != null && parentForm.Text.Contains("编辑JSON文件"))
                {
                    // 在JSON编辑窗口中，允许滚轮功能
                    base.WndProc(ref m);
                    return;
                }
                
                // 在表单编辑窗口中，禁用滚轮功能
                return;
            }
            base.WndProc(ref m);
        }
    }

    // 自定义NumericUpDown，禁用鼠标滚轮
    public class NoWheelNumericUpDown : NumericUpDown
    {
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            // 不调用基类方法，从而禁用滚轮功能
            // base.OnMouseWheel(e);
        }

        protected override void WndProc(ref Message m)
        {
            // WM_MOUSEWHEEL = 0x020A
            if (m.Msg == 0x020A)
            {
                // 检查是否在JSON编辑窗口中
                Form parentForm = this.FindForm();
                if (parentForm != null && parentForm.Text.Contains("编辑JSON文件"))
                {
                    // 在JSON编辑窗口中，允许滚轮功能
                    base.WndProc(ref m);
                    return;
                }
                
                // 在表单编辑窗口中，禁用滚轮功能
                return;
            }
            base.WndProc(ref m);
        }
    }

    // 自定义DateTimePicker，禁用鼠标滚轮
    public class NoWheelDateTimePicker : DateTimePicker
    {
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            // 不调用基类方法，从而禁用滚轮功能
            // base.OnMouseWheel(e);
        }

        protected override void WndProc(ref Message m)
        {
            // WM_MOUSEWHEEL = 0x020A
            if (m.Msg == 0x020A)
            {
                // 检查是否在JSON编辑窗口中
                Form parentForm = this.FindForm();
                if (parentForm != null && parentForm.Text.Contains("编辑JSON文件"))
                {
                    // 在JSON编辑窗口中，允许滚轮功能
                    base.WndProc(ref m);
                    return;
                }
                
                // 在表单编辑窗口中，禁用滚轮功能
                return;
            }
            base.WndProc(ref m);
        }
    }

    // 自定义CheckBox，禁用鼠标滚轮
    public class NoWheelCheckBox : CheckBox
    {
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            // 不调用基类方法，从而禁用滚轮功能
            // base.OnMouseWheel(e);
        }

        protected override void WndProc(ref Message m)
        {
            // WM_MOUSEWHEEL = 0x020A
            if (m.Msg == 0x020A)
            {
                // 检查是否在JSON编辑窗口中
                Form parentForm = this.FindForm();
                if (parentForm != null && parentForm.Text.Contains("编辑JSON文件"))
                {
                    // 在JSON编辑窗口中，允许滚轮功能
                    base.WndProc(ref m);
                    return;
                }
                
                // 在表单编辑窗口中，禁用滚轮功能
                return;
            }
            base.WndProc(ref m);
        }
    }

    // 用于ComboBox显示枚举值
    public class ComboBoxItem
    {
        public object Value { get; set; }
        public string Text { get; set; }

        public override string ToString()
        {
            return Text;
        }
    }
}

